﻿using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.EquipmentManagement.Model;
using B.MESUI.Login.ProdManagement.Model;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static B.MESUI.Login.WareHouseDefinitionForm;
using static DevExpress.Drawing.Printing.Internal.DXPageSizeInfo;



namespace B.MESUI.Login.ProdManagement.Lock
{
    public partial class UnProductLockForm : DevExpress.XtraEditors.XtraForm
    {
        DeviceGridPanel devicePanel;
        public UnProductLockForm()
        {

            InitializeComponent();

            // 1. 创建控件实例
            devicePanel = new DeviceGridPanel();
            devicePanel.Dock = DockStyle.Fill;

            // 2. 加入到主窗体的某个Panel或直接加到this.Controls
            this.Controls.Add(devicePanel);
            // 3. 绑定事件
            devicePanel.AddClicked += (s, e) => { /* 新增逻辑 */ };
            devicePanel.ExportClicked += (s, e) => { /* 导出逻辑 */ };
            devicePanel.DeleteClicked += async (s, e) =>
            {
                await HandleDeleteAsync();
            };
            devicePanel.EditClicked += (s, e) => { MessageBox.Show("你点击的ID是：" + e); };
            // 4. 绑定分页事件（数据获取）
            devicePanel.OnPageChanged += async (pageIndex, pageSize) =>
            {
                // 这里调用你的后端API
                var result = await GetDeviceTypeListAsync(pageIndex, pageSize); // 你的API
                devicePanel.SetDataSource(result.Data);
                devicePanel.SetPageInfo(pageIndex, pageSize, result.TotalCount);
                devicePanel.gridView.Columns["Id"].Visible = false;
                // 设置列名（两处都需要改，这个是分页显示）
                var columnCaptions = new Dictionary<string, string>
                { 

                    //格式{ "Id", "设备编号" },
                    // 其他字段...
                    { "PRODUCTID", "产品锁定id" },
                    { "PRODUCE_TYPE", "类型" },
                    { "CODEID", "编码" },
                    { "PRODUCTION_PROCESSES", "工序" },
                    { "LOCK_STARTTIME", "锁定开始时间" },
                    { "LOCL_ENDTIME", "锁定结束时间" },
                    { "LOCK_REASON", "锁定原因" },
                    { "LOCK_PEOPLE", "锁定人" },
                    { "LOCK_STATUES", "状态" },
                    { "CREATETIME", "时间" },
                    { "CREATOR", "创建人" },
                    { "CREATE_TIME", "创建时间" },
                    { "UPDATOR", "修改人" },
                    { "UPDATE_TIME", "修改时间" },
                };
                devicePanel.SetColumnCaptions(columnCaptions);
            };

        }




        private async void UnProductLockForm_Load(object sender, EventArgs e)
        {
            //devicePanel.btnDelete.Text = "解锁";

            //放在load事件里
            // 首次加载第一页
            devicePanel.btnDelete.Text = "解锁"; 
            devicePanel.btnAdd.Visible=false;
            devicePanel.btnExport.Visible = false;
            var result = await GetDeviceTypeListAsync(1, 20);//默认1页20条
            devicePanel.SetDataSource(result.Data);
            devicePanel.SetPageInfo(1, 20, result.TotalCount);
            devicePanel.gridView.Columns["Id"].Visible = false;
            // 设置列名（两处都需要改，这个是初始化）
            var columnCaptions = new Dictionary<string, string>
            {
                //格式{ "Id", "设备编号" },

                // 其他字段...
                { "PRODUCTID", "产品锁定id" },
                { "PRODUCE_TYPE", "类型" },
                { "CODEID", "编码" },
                { "PRODUCTION_PROCESSES", "工序" },
                { "LOCK_STARTTIME", "锁定开始时间" },
                { "LOCL_ENDTIME", "锁定结束时间" },
                { "LOCK_REASON", "锁定原因" },
                { "LOCK_PEOPLE", "锁定人" },
                { "LOCK_STATUES", "状态" },
                { "CREATETIME", "时间" },
                { "CREATOR", "创建人" },
                { "CREATE_TIME", "创建时间" },
                { "UPDATOR", "修改人" },
                { "UPDATE_TIME", "修改时间" },

            };
            devicePanel.SetColumnCaptions(columnCaptions);

        }
        // 伪代码，实际根据你的后端API来写
        private async Task<(List<ProductLockDto> Data, int TotalCount)> GetDeviceTypeListAsync(int pageIndex, int pageSize)
        {
            // 调用后端接口，返回数据和总数
            using (var client = new HttpClient())
            {
                // 替换为你的API实际地址
                string url = $"http://39.103.49.30:9983/api/ProductLock/GetProductLockList?PageIndex={pageIndex}&PageSize={pageSize}";
                //替换为自己的传值方式
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                //替换为你自己的数据模型
                var result = JsonConvert.DeserializeObject<ApiPaging<ProductLockDto>>(json);
                foreach (var item in result.PageDatas)
                {
                    item.Id = item.PRODUCTID;
                }
                return (result.PageDatas, result.TotalCount);
            }
        }      
        // 刷新当前页面数据
        private async Task RefreshCurrentPageAsync()
        {
            try
            {
                var result = await GetDeviceTypeListAsync(devicePanel.PageIndex, devicePanel.PageSize);
                devicePanel.SetDataSource(result.Data);
                devicePanel.SetPageInfo(devicePanel.PageIndex, devicePanel.PageSize, result.TotalCount);
                devicePanel.gridView.Columns["Id"].Visible = false;

                // 设置列标题
                var columnCaptions = new Dictionary<string, string>
                {
                    { "PRODUCTID", "产品锁定id" },
                    { "PRODUCE_TYPE", "类型" },
                    { "CODEID", "编码" },
                    { "PRODUCTION_PROCESSES", "工序" },
                    { "LOCK_STARTTIME", "锁定开始时间" },
                    { "LOCL_ENDTIME", "锁定结束时间" },
                    { "LOCK_REASON", "锁定原因" },
                    { "LOCK_PEOPLE", "锁定人" },
                    { "LOCK_STATUES", "状态" },
                    { "CREATETIME", "时间" },
                    { "CREATOR", "创建人" },
                    { "CREATE_TIME", "创建时间" },
                    { "UPDATOR", "修改人" },
                    { "UPDATE_TIME", "修改时间" },
                };
                devicePanel.SetColumnCaptions(columnCaptions);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"刷新数据时发生错误：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UnProductLockForm_Leave(object sender, EventArgs e)
        {

        }

        // 处理删除操作
        private async Task HandleDeleteAsync()
        {
            try
            {
                // 获取选中的ID
                string selectedIds = devicePanel.GetSelectedIdsString();
                
                if (string.IsNullOrEmpty(selectedIds))
                {
                    XtraMessageBox.Show("请先选择要解锁的产品！", "提示", 
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确认删除
                var result = XtraMessageBox.Show(
                    $"确定要解锁选中的 {selectedIds.Split(',').Length} 个产品吗？", 
                    "确认解锁", 
                    MessageBoxButtons.YesNo, 
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    // 调用解锁接口
                    bool success = await UnlockProductsAsync(selectedIds);
                    
                    if (success)
                    {
                        XtraMessageBox.Show("产品解锁成功！", "成功", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 刷新当前页面数据
                        await RefreshCurrentPageAsync();
                    }
                    else
                    {
                        XtraMessageBox.Show("产品解锁失败，请重试！", "错误", 
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"解锁过程中发生错误：{ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 调用后端解锁接口
        private async Task<bool> UnlockProductsAsync(string productIds)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    string url = "http://39.103.49.30:9983/api/ProductLock/UnProductLock";
                    
                    // 注意参数名和格式
                    var requestData = new
                    {
                        productiDs = productIds.Split(',') // 变成字符串数组
                    };
                    
                    var json = JsonConvert.SerializeObject(requestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    
                    var response = await client.PutAsync(url, content);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var responseJson = await response.Content.ReadAsStringAsync();
                        // 这里可以根据实际返回内容判断
                        return true;
                    }
                    else
                    {
                        var errorMsg = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"解锁失败，后端返回：{errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"解锁产品时发生错误：{ex.Message}");
                return false;
            }
        }



    }
}